package com.menghao.sso.client.filter;

import com.menghao.sso.client.model.ValidateBean;
import com.menghao.sso.client.util.CommonUtils;
import com.menghao.sso.client.validation.TicketValidator;
import com.menghao.sso.client.validation.ValidationException;
import lombok.Setter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>对ST合法性校验.<br>
 *
 * @author menghao.
 * @version 2017/11/15.
 */
public class CheckTicketFilter extends AbstractCasFilter {

    @Setter
    private TicketValidator ticketValidator;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        // 创建服务验证请求
        String serviceTicket = request.getParameter(CommonUtils.ST_ID);
        String originalRequest = makeOriginalRequest(request, response);
        String validateRequest = makeValidateSTRequest(originalRequest);
        // 发送验证请求
        try {
            ValidateBean validateBean = ValidateBean.builder().url(validateRequest).serviceTicket(serviceTicket).build();
            Boolean success = ticketValidator.validate(validateBean);
            if (success) {
                filterChain.doFilter(request, response);
                return;
            }
        } catch (ValidationException e) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            log.warn(e, e);
            throw new ServletException(e);
        }
    }

}
